<template>
  <div id="app">
    <!-- //isLogin初始值为false，未登陆时盒子隐藏 -->
    <div v-if="isLogin">
      <!-- //头部组件 -->
      <app-header></app-header>
      <!-- //左侧边 -->
      <sidebar></sidebar>
      <div :class="$style.background">
        <breadcrumb></breadcrumb>
        <div :class="$style.content" :style="customStyle">
          <keep-alive>
            <router-view @onCustomStyle="_isCustomStyle" v-if="$route.meta.keepAlive"></router-view>
          </keep-alive>
          <router-view @onCustomStyle="_isCustomStyle" v-if="!$route.meta.keepAlive"></router-view>
        </div>
      </div>
    </div>

    <login v-if="!isLogin"></login>
    <!-- <call-in></call-in>电话服务 -->

    <!-- <Drag v-if="isLogin">
      <iframe :class="$style.chatRoom" :src="chatRoomBaseUrl + cuKfid" frameborder="0"></iframe>
    </Drag> -->
    <!-- <remark-dialog ref="remark"></remark-dialog> -->
    <call-time v-if="isLogin"></call-time><!--通话时长-->
    <!-- <el-dialog title="呼叫未接通的通话内容" :visible.sync="wjt.dialogVisible" :close-on-click-modal="false">
      <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="wjt.content">
      </el-input>
      <p :class="$style.txtRight">
        <el-button type="primary" @click="handleSubmitWJT">提交</el-button>
      </p>
    </el-dialog> -->
  </div>
</template>

<script>
import { cookie } from 'vux'
import Login from './pages/login/index.vue'
import AppHeader from './components/header/index.vue'
import Sidebar from './components/sidebar/index.vue'
import Breadcrumb from './components/breadcrumb/index.vue'
//import CallIn from './components/callin/index.vue'
// import Drag from './components/drag/index.vue'
// 备注弹窗
// import RemarkDialog from './components/remark/index.vue'
// 通话时长
import CallTime from './components/callTime/index.vue'
export default {
  name: 'app',
  components: {
    AppHeader,
    Sidebar,
    Breadcrumb,
    Login,
    
    // Drag,
    // RemarkDialog,
    CallTime
  },
  data() {
    const url = 'http://122.228.132.78:885/w6h8y3_n7s4d/customerchat.aspx?kfid='
    //const url = 'http://i.wsloan.com/w6h8y3_n17s4d/customerchat.aspx?kfid='
    return {
      customStyle: null,
      chatRoomBaseUrl: url,
      callState:'',
      // 防止重复的命令
      lock:false,
      isRing:false,
    }
  },
  computed: {
    //是否登录
    isLogin() {
      return this.$store.getters.getIsLogin //默认状态是false
    },
    userInfo() {
      return this.$store.getters.getUserInfo //默认用户信息为空
    },
    wsData() {
      return websocket.data
    },
    cuKfid() {
      const  {userName,id } = this.$store.getters.getUserInfo  //拿到用户信息
      return  this.$store.getters.getUserInfo.id  //返回登陆用户id
      // return '17'
    }
  },
  watch: {
    // userInfo: function(val) {
    //   websocket.userInfo = val
    //   if (val) {
    //     myws.init(val);
    //     console.log('用户信息', this.$store.getters.getUserInfo)
    //   }
    // },
    wsData(cmd) {
      const {userGroup} = this.userInfo
      const initCallMsg = {
        callType: '',
      }
      const {telMsg} = this.$store.getters.callMsg
      if (websocket.state === 1) {
        /**
         *  根据返回的值进行处理
         *  主要功能: 呼出  呼入[暂不能处理]
         * **/
        /**
         * 根据Ringing返回的phone是否是手机号来判断是呼入还是呼出
         *
        */
        /*==============模拟场景==================*/
        // if(cmd.action === 'Ringing' && !this.isRing){
        if(!this.isRing && (cmd.action === 'callout' || cmd.action === 'callin')){
          // 如果推送的命令是Ringing，并且命令中包含的是手机号则为呼出,否则则为呼入
          // this.callState = this.isPhone(cmd.phone) ? 'callout' : 'callin'
          this.callState = cmd.action
          this.isRing = true
        }
        //  呼出
        // 暂时只考虑呼出
        // if(cmd.action === 'callout' && !this.lock && this.isPhone(cmd.phone)){
        if(!this.lock && cmd.action === 'up'){
          this.lock = true
          this.callHandler(cmd)
        } else if(cmd.action === 'hangup' && this.lock){
          // if(userGroup === '业务组'){
          //   this.$store.dispatch('updateCallMsg',initCallMsg)
          //   return
          //   this.$refs['remark'].remarkDialog(telMsg.id)
          // }
          this.lock = false
          this.isRing = false
          this.$toast({
            message:'挂机成功'
          })

          // if(userGroup === '业务组'){
          this.$store.dispatch('updateCallMsg',initCallMsg)
          // }

          // 添加通话提示信息
          this.$store.dispatch('updateCallInfo','通话尚未建立连接')
          // 更新挂机行为
          this.$store.dispatch('updateIsHangup',true)

          // 挂机的待打尾处理
          this.$store.dispatch('updateDaida', null)
        }
      }
    },
    isLogin(val){
      if(val){
        this.getLineup();
        this.getKf();
        this.getMenu();
        //更新当前组的所有客服
        this.getCurGroup()

        // 时间记录维持
        // myws.init(val);
        console.log('用户信息', this.$store.getters.getUserInfo)
      }
      if(this.userInfo.power < 3 || this.userInfo.power === 5){
       this.getSeat()
      } 
    },
  },
  methods: {
    _isCustomStyle(customStyle) {
      if (customStyle) {
        this.customStyle = customStyle
      }
    },
    isPhone(val){
      return new RegExp('^((13[0-9])|(15[^,\\D])|(17[0-9])|(147)|(18[0-9]))\\d{8}$').test(val)
    },
    callHandler(cmd){
      this.getCurCallMsg(cmd)
    },
    async getCurCallMsg(cmd){
      const {phone} = cmd
      const action = this.callState
      const {id,userGroup} = this.userInfo
      const baseUrl = window.ipurl
      try{
        const {data} = await this.$get(this,{
          api:'getUserInfo',
          data:{
            phone:phone.toString(),
            ccmd:action,
            adminid:id.toString(),
          },
        },baseUrl)
        if (data.state === 0) {
          this.$toast({
            message: '开始通话'
          })
          // 添加通话提示信息
          this.$store.dispatch('updateCallInfo','通话已建立连接')
          // 更新挂机行为
          this.$store.dispatch('updateIsHangup', false)
          // 由于不限制提交通话内容，导致未提交通话内容之前仍可以打电话，作如下处理
          const callMsg = {
            telMsg: data.content,
            leadInMsg: data.content,
            mobile: phone,
            callType: action,
            // curRecordFile: v3,
            createdTime: Date.now(),
            serviceForm: {
              que1: '',
              que2: '',
              content: '',
            }
          }

          // 新功能添加--通话详情标签页
          // if(userGroup !== '业务组'){
          if(userGroup === '答疑组'){
            const tmpo = Object.assign([],this.$store.getters.callList)
            tmpo.data.push(callMsg)
            tmpo.curIndex++
            this.$store.dispatch('updateCallList', tmpo)
          }
          //

          this.$store.dispatch('updateCallMsg', callMsg)
          //

          // 业务组不跳详情页
          if(userGroup === '业务组' || userGroup === '回访组'){
            return
          }
          this.$router.push('/call-center/call-detail')
          return
        }
        this.$warn('getUserInfo接口报错')
      }catch(e){
        this.$warn('getUserInfo:', e.message)
      }
    },
    async getLineup() {
      // 获得组id: 组名字
      let { data } = await this.$get(this, {
        api: 'ajaxapi/ipcczb.do', data: {
        }
      })
      if (data.state === 0) {
        this.$store.dispatch('updateGroup', data.content)
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    async getKf() {
      // 已筛选客服，back-log,call,call-total
      const { userGroupId, power } = this.$store.getters.getUserInfo
      let { data } = await this.$get(this, {
        api: 'ajaxapi/loadkf.do', data: {
          // sessionId: this.userInfo.sessionId
          groupId: power !== 1 ? userGroupId : ''
        }
      })
      if (data.state === 0) {
        this.$store.dispatch('updateKf', data.content)
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    async getSeat() {
      
      // 与websock，传过来的进行匹配，
      let { data } = await this.$get(this, {
        api: 'ajaxapi/man_age.do', data: {
        }
      })
      
      if (data.state === 0) {
        this.seatsKf = data.content;
        this.$store.state.user.seatKf=this.seatsKf
        
      } else {
        this.$toast({
          message: data.message
        })
      }
    },
    async getCurGroup() {
      try {
        const { userGroupId } = this.$store.getters.getUserInfo
        const { data } = await this.$get(this, {
          api: 'ajaxapi/loadAllKf.do',
          data: {
            groupId: userGroupId
          }
        })
        if (data.state === 0) {
          this.$store.dispatch('updateCurGroup', data.content)
        }
      } catch (e) {
        this.$warn('系统ajaxapi/loadAllKf.do接口报错')
      }
    },
    async getMenu(){
      this.$get(this,{
            api:"/user/fetchRoleMenu.do"
          }).then((data)=>{
            if(data.data.state ===0){
              this.$store.dispatch('updataMenu', data.data.content.menu)
            }
            console.log('侧边栏状态',this.$store.getters)
          })
    }
  },
  mounted() {
    const callMsg = window.localStorage.getItem('callMsg')
    if (callMsg) {
      this.$store.dispatch('updateCallMsg', JSON.parse(callMsg))
    }
    const callList = window.localStorage.getItem('callList')
    if (callList) {
      this.$store.dispatch('updateCallList', JSON.parse(callList))
    }
    if(this.userInfo.power < 3 || this.userInfo.power === 5){
       this.getSeat()
      }
    //
    // this.test()
  },
}

</script>
<style lang="scss" module>
.background {
  background: #f5f8fb;
  box-sizing: border-box;
  padding: 20px;
  padding-left: 250px;
  padding-right: 60px;
  height: calc(100vh - 80px);
  position:relative;
}

.content {
  background: #fff;
  height: calc(100% - 10px);
  width: 100%;
  box-sizing: border-box;
  margin-top: 10px;
  overflow-y: scroll;
  border-radius: 5px;
  border: 1px solid #dddfe6;
}

.chatRoom {
  width: 100%;
  height: 100%;
}
.txtRight{
  text-align:right;
  margin-top:10px;
}
</style>

<style src="../style/index.scss" lang="scss"></style>
